export class SimpleWebSocket {
    constructor(url){
        this.url = url;
        this.socket=null;
        // 用于存储用户自定义的消息相应函数
        this.onMessageCallback = null;
    }
    connect(){
        this.socket=new WebSocket(this.url);
        this.socket.onopen = () => {
            console.log("WebSocket连接已打开");
        }
        this.socket.onmessage=(event)=>{
            if(this.onMessageCallback){
                this.onMessageCallback(event.data);
            }
        }
        this.socket.onclose = () => {
            console.log("WebSocket连接已关闭");
        }
        this.socket.onerror = (error) => {
            console.error("WebSocket发生错误:", error);
        }
    }
    send(message){
        if(this.socket && this.socket.readyState===WebSocket.OPEN){
            this.socket.send(message);
        }

    }
    setOnMessagge(callback){
        this.onMessageCallback=callback;
    }
    disconnect(){
        if(this.socket){
            this.socket.close();
        }
    }

}